package com.augurit.gzcgwsp.jzfqwczzpfsn.web;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ProcessEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;
import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.jzfqwczzpfsn.entity.YwYnJzfqwczzPfsn;
import com.augurit.gzcgwsp.jzfqwczzpfsn.service.IYwYnJzfqwczzPfsnService;
import com.augurit.gzcgwsp.jzfqwczzpfsn.service.IYwYnJzfqwczzPfsnyqService;
import com.augurit.gzcgwsp.jzfqwczzpfsn.web.form.YwYnJzfqwczzPfsnForm;
import com.augurit.gzcgwsp.lhsp.service.IProcessInstanceService;
import com.augurit.gzcgwsp.lhsp.web.form.LhspSendItemNoticeForm;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.qyzz.web.YwRqQyzzInfoAction;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.ywcmn.convert.YwComSjcllistConvertor;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjclService;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjcllistOtherService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjclForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjcllistForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjcllistOtherForm;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientAction;

@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "yw-yn-jzfqwczz-pfsnyq.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczzPfsn/YwYnJzfqwczzPfsnyq.jsp"),
	@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczzPfsn/YwYnJzfqwczzPfsnyq-input.jsp"),
	@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
    @Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP),
    @Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/make-noline-document.jsp"),
    @Result(name = "preViewFh", location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczzPfsn/preViewFh.jsp"),
    @Result(name = "preViewCzz", location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczzPfsn/preViewCzz.jsp"),
    @Result(name = "printzs", location = "/gzcgwsp/wfex/client/wf-printExcelEx.jsp")
})
public class YwYnJzfqwczzPfsnyqAction extends WfBusClientAction<YwYnJzfqwczzPfsnForm>{
	private static final Logger log=Logger.getLogger(YwRqQyzzInfoAction.class);
	@Autowired
	private IYwYnJzfqwczzPfsnService ywYnJzfqwczzPfsnService;
	@Autowired
	private IYwYnJzfqwczzPfsnyqService ywYnJzfqwczzPfsnyqService;
    @Autowired
    private IWfBusTemplateService wfBusTemplateService;
	@Autowired
	private IYwComSjcllistOtherService ywComSjcllistOtherService;
    @Autowired
    private ISysCodeService syscodeService;    
    @Autowired
    private IWfServiceEX wfServiceEX;
    @Autowired
    private IYwPrintDocService ywPrintDocService;    
    @Autowired
    private IWfService wfService;
    @Autowired
    private IWfBusTemplateServiceEX wfBusTemplateServiceEX;
    @Autowired
    private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;
    @Autowired
    private IOaDocCodeServiceEX oaDocCodeServiceEX;
    @Autowired
    private IYwComSjclService ywComSjclService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private IProcessInstanceService processInstanceService;
	private YwYnJzfqwczzPfsnForm form;
	private Long id;
	private Long[] checkedIds;
	private Page<YwYnJzfqwczzPfsnForm> page = new Page<YwYnJzfqwczzPfsnForm>(10);

    /**
     * 保存业务并关联流程实例
     */
    public String wfBusSave() {
    	try{
        WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)ywYnJzfqwczzPfsnyqService, form, YwYnJzfqwczzPfsn.class.getSimpleName());
        String isYsl = super.getParameter("isYsl");
        if (StringUtils.isNotBlank(isYsl) && "1".equals(isYsl)) {
        	String executionId =  processEngine.getHistoryService().createHistoryTaskQuery().taskId(task.getTaskInstDbid().toString()).uniqueResult().getExecutionId();
            processEngine.getExecutionService().jumpToActivity(executionId, "cksa");
            form.setYsl(null);
            ywYnJzfqwczzPfsnyqService.changeYslState(form.getId(), null,"");
        }
        WfUtils.renderWfBusSaveJson(task, form);
    	}catch (Exception e) {
    		e.printStackTrace();
      		WfUtils.renderWfFailtureJson("请检查输入内容长度是否过大!");
   		}
        return null;
    }
    
    /**
	 * 窗口保存联合审批案件
	 * @return
	 */
	public String saveLhspData() throws Exception{
		String lhspId = super.getParameter("lhspId");		
		String ShenQingDanWeiR = super.getParameter("ShenQingDanWeiR");//申请单位（人）
		String ProContactName = super.getParameter("ProContactName");//联系人姓名
		String ProContactPhone = super.getParameter("ProContactPhone");//联系人手机
		String ProProjectName = super.getParameter("ProProjectName");//项目名称
		String ProConstructionUnitAddress = super.getParameter("ProConstructionUnitAddress");//项目地址
//		System.out.println("lhspId = "+lhspId);
//		System.out.println("ShenQingDanWeiR = "+ShenQingDanWeiR);
//		System.out.println("ProContactName = "+ProContactName);
//		System.out.println("ProContactPhone = "+ProContactPhone);
//		System.out.println("ProProjectName = "+ProProjectName);
//		System.out.println("ProConstructionUnitAddress = "+ProConstructionUnitAddress);
		form.setSarq(new Date());//
		form.setLarq(form.getSarq());//
//		form.setSsq(getLoginUser().getOrg().getOrgName().substring(0,3));//
		form.setJsdwLxr(ProContactName);//建设单位联系人
		form.setJsdwLxrLxdh(ProContactPhone);//建设单位联系人电话
		form.setSqdw(ShenQingDanWeiR);//申请单位
		form.setGcmc(ProProjectName);//工程名称
		form.setGcdz(ProConstructionUnitAddress);//工程地址
		
		WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)ywYnJzfqwczzPfsnyqService, form, YwYnJzfqwczzPfsn.class.getSimpleName());
		if(task!=null){//修改答复时间
			String procInstId = task.getProcInstId();
			processInstanceService.updateDfsjDate(form.getSarq(), procInstId);
			if(StringUtils.isNotBlank(lhspId)){
				form.setLhspId(Long.parseLong(lhspId));
				processInstanceService.changeIsLhsp(lhspId);
			}
	    }
		getResponse().getWriter().print("success");
		return null;
	}
    
    public String wfBusYslTuih() throws Exception {
    	try {
    		ywYnJzfqwczzPfsnyqService.wfBusYslTuih(form, this.getLoginUser());
			WfBusSaveResult result = new WfBusSaveResult(true, null);
			result.setTask(new WfBusInstanceTaskForm());
			Struts2Utils.renderJson(result);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
        return null;
    }
    /**
     * 控件套打证书
     * @return
     */
    public String printZs(){
    	 String tempPath="Templates/ynpfczz.xls";
        String context=getRequest().getSession().getServletContext().getRealPath("");
        tempPath=this.ywYnJzfqwczzPfsnyqService.printZs(form,context);
        getRequest().setAttribute("templateFilePath",tempPath);
    	return "printzs";
    }
    
    /**
     * 出证
     */
    public String printcz() throws Exception {
    	String taskId=getRequest().getParameter("taskInstDbid");
		if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			String activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
    	if(form.getId() != null && form.getId() > 0){
    		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
        	if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
    			return WfConstant.PRINT_DIR;
    		}
    	}
    	try{//构造数据,放入书签中
             Map<String, String> variables=WfUtilsEX.buildMap(form,"yyyy年MM月dd日");
             if("sjtzs".equals(form.getFileCode())){
            	  String acceptNo=this.ywPrintDocService.updateAcceptNo(form.getTemplateCode(),String.valueOf(form.getId()));
                  if(StringUtils.isNotBlank(acceptNo)){
              		variables.put("acceptNo", acceptNo);
              		variables.put("serialNo", acceptNo);
              		variables.put("acceptNo1", acceptNo);
              		variables.put("serialNo1", acceptNo);
              		variables.put("acceptNo2", acceptNo);
              		variables.put("acceptNo3", acceptNo);
              		variables.put("serialNo2", acceptNo);
              	}
             }
              //获取收件材料数据放到map中
             List<YwComSjcllistForm> sjlist=this.ywYnJzfqwczzPfsnService.getSjcls(form);
             YwComSjclForm fkForm = new YwComSjclForm();
             fkForm.setFkid(form.getQyid());
             fkForm.setAjid(form.getId());
             fkForm.setTplcode(getTemplateCode());
             YwComSjcllistForm sjclform=new YwComSjcllistForm();
             sjclform.setAjid(form.getId());
             sjclform.setQyid(form.getQyid());
             sjclform.setBelongType(form.getGclb());
             sjclform.setTplcode(form.getTemplateCode());
             List<YwComSjclForm> sjclTpl = ywComSjclService.getList(fkForm);
             List<YwComSjcllistOtherForm> sjclList = ywComSjcllistOtherService.getList(sjclform);
             List<YwComSjcllistForm> others=YwComSjcllistConvertor.convertOtherSjcllistFormListToSjcllistFormList(sjclList);
             sjlist.addAll(others);
             int i=1;
             for(YwComSjcllistForm sjcl:sjlist){
           	  for (YwComSjclForm tplForm : sjclTpl) {
           		  if (tplForm.getTplid() != null &&
           				  sjcl.getId().longValue() == tplForm.getTplid().longValue()) {
           			  sjcl.setSfdz("1");
           	     }
           	  }
           	  //收件材料有些只有名称
           	  if(sjcl.getFyjs()!=null && sjcl.getFyjs()>0){
           		  Long fs=sjcl.getYjs()+sjcl.getFyjs();
           		  Long fyjs=sjcl.getFyjs();
           		  String zzcl="";
           		  //if(!"0".equals(sjcl.getSfdz())){
     					zzcl="√";
     				//}
     				  variables.put("no"+i,String.valueOf(i));
   	     			  variables.put("tplname"+i,sjcl.getTitle());
   	     			  variables.put("tplname_"+i,sjcl.getTitle());
   	     			  variables.put("no_"+i,String.valueOf(i));
   	           		  variables.put("fs"+i,String.valueOf(fs));
   	           		  variables.put("zzcl"+i,String.valueOf(zzcl));
   	           		  variables.put("fyjs"+i,String.valueOf(fyjs));
   	           		  variables.put("fs_"+i,String.valueOf(fs));
   	           		  variables.put("zzcl_"+i,zzcl);
   	           		  variables.put("fyjs_"+i,String.valueOf(fyjs));
           		  i++;
           	  }
             }
     		String area=this.ywYnJzfqwczzPfsnService.getArea(form.getId());
    		String gcdz=form.getGcdz();
    		String orgname="";
    		String areazfj="";
    		String areaorg="";
    		if(StringUtils.isNotBlank(area)){
    			variables.put("orgjc","("+area.substring(0,2)+")");
    			orgname=area+"余泥管理所";
    		}else{
    			orgname="广州市余泥渣土排放管理处办公室";
    			
    		}
    		 variables.put("orgname",orgname);
             variables.put("ysgs1", form.getYsgs());
             ServletActionContext.getRequest().setAttribute(WfConstant.PRINT_BUFFER, variables);
         }
         catch(Exception e){
             e.printStackTrace();
         }
         return WfConstant.PRINT;
    }
    
    public String makeDocument() throws Exception {
        if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
            String redHeadFilePath = wfBusTemplateServiceEX.getPrintTemplatePath(Long.parseLong(form.getRedHeadFileId()));
            log.info("readheadFile----->"+redHeadFilePath);
            form.setRedHeadFilePath(redHeadFilePath);
        }
         //加载收件通知书里面的附件
		 String isred=getRequest().getParameter("isred");
		 //如果要打印红头
		 if("yes".equals(isred)){
			 String redHeadFilePath = wfBusTemplateServiceEX.getRedFile(form.getTemplateCode());
		      form.setRedHeadFilePath(redHeadFilePath);
		 }
        String templateCode = getTemplateCode();
        if(templateCode != null && templateCode.trim().length() > 0){
            String printTemplatePath = wfBusTemplateServiceEX.getPrintTemplatePath(templateCode, WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
            form.setTemplatePath(printTemplatePath);
            WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX = 
            	(WfTemplateAttachmentRefFormEX)wfTemplateAttachmentRefServiceEX.get(Long.parseLong(form.getZhengwenFileId()));
            String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath() + "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
            form.setZhengwenPath(zhengwenPath);
            form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
            form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
            if(form.getCurSeq()==null){
                Long seq=oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),form.getId());
    	        if(seq.intValue()<10){
	        	  form.setCurSeq("0"+String.valueOf(seq));
		        }else{
		        	  form.setCurSeq(String.valueOf(seq));
		        }
            }     
            
            WfUtilsEX.wfBusPrint(form);
            getRequest().setAttribute("isunified", false);//是否全委统一
            BaseAction.getRequest().setAttribute("seq", form.getCurSeq());
            BaseAction.getRequest().setAttribute("templateFilePath",zhengwenPath);
            BaseAction.getRequest().setAttribute("fileCode", wfTemplateAttachmentRefFormEX.getFileCode());
            BaseAction.getRequest().setAttribute("entityId", form.getId());
            BaseAction.getRequest().setAttribute("templateId", wfTemplateAttachmentRefFormEX.getId());
//            BaseAction.getRequest().setAttribute("busType", OaFawen.class.getSimpleName());
        }
        return WfConstant.MAKE_DOCUMENT;
    }
    
    /**
	 * 预览复函或者处置证
	 * @return
	 */
	public String preViewFhOrCzz(){
		String templateCode = getRequest().getParameter("templateCode");
		getRequest().setAttribute("templateCode", templateCode);
		String flag = getRequest().getParameter("flag");
		String taskInstDbid = getRequest().getParameter("taskInstDbid");
		getRequest().setAttribute("taskInstDbid", taskInstDbid);
		if("czz".equals(flag)){
			return "preViewCzz";
		}else{
			return "preViewFh";
		}
	}
	
	/**
	 * 保存复函
	 * @return
	 * @throws IOException 
	 */
	public String saveFh() throws IOException{
//	    Map map=getMapByRequest(getRequest());
//        setValueByMap(form, map);
//		String flag=getRequest().getParameter("flag");
        String result="true";
        try {
        	ywYnJzfqwczzPfsnyqService.save(form);
        } catch (Exception e) {
            result="false";
        }
        getResponse().getWriter().print(result);
	    return null;
	}
	
	/**
	 * 保存处置证
	 * @return
	 * @throws IOException 
	 */
	public String saveCzz() throws IOException{
//	    Map map=getMapByRequest(getRequest());
//        setValueByMap(form, map);
//		String flag=getRequest().getParameter("flag");
        String result="true";
        try {
        	ywYnJzfqwczzPfsnyqService.save(form);
        } catch (Exception e) {
            result="false";
        }
        getResponse().getWriter().print(result);
	    return null;
	}
    
	@Override
	public String list() throws Exception {
		ywYnJzfqwczzPfsnyqService.search(page, form);
		return SUCCESS;
	}
	
	@Override
    public String input() throws Exception {
        this.initWfOpinions();
        
        getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
        
        List<SysCodeForm> docTypeList = syscodeService.getItems("YW_QY_ZZDJ");
        getRequest().setAttribute("qyzzdj", docTypeList);
        List<SysCodeForm> gclbList = syscodeService.getItems("YW_GCLB");
        getRequest().setAttribute("gclbList", gclbList);
        List<SysCodeForm> jmfeList = syscodeService.getItems("YW_JMFE");
        getRequest().setAttribute("jmfeList", jmfeList);
        return INPUT;
    }

	/**
	 * �������������޸ĵ�Form����
	 */
	@Override
	public String save() throws Exception {
		ywYnJzfqwczzPfsnyqService.save(form);
		return RELOAD;
	}

	/**
	 * ɾ��һ����¼
	 */
	@Override
	public String delete() throws Exception {
		ywYnJzfqwczzPfsnyqService.delete(id);
		return RELOAD;
	}
	
	/**
	 * ɾ�������¼
	 */
	@Override
	public String deleteMore() throws Exception{
		ywYnJzfqwczzPfsnyqService.delete(checkedIds);
		return RELOAD;
	}
	
	   @Override
	    protected void prepareModel() throws Exception {
	        if(id != null){
	            form = ywYnJzfqwczzPfsnyqService.get(id);
	        }
	        else
	            form = new YwYnJzfqwczzPfsnForm();
	        
	        if(StringUtils.isBlank(form.getGclb())){
	        	form.setGclb("1");
	        }
	        if(form.getLhspId() != null){
	        	LhspSendItemNoticeForm sendItemNoticeForm = processInstanceService.get(form.getLhspId());
	        	this.getRequest().setAttribute("form", sendItemNoticeForm);
	        }
	        if (StringUtils.isBlank(form.getAcceptNo())) {
	        	String rq = DateUtilsEX.getYearAndMonthAndDay();
	        	form.setAcceptNo("gz26"+rq+"XXXXX");
	        }

	        if (StringUtils.isBlank(form.getSjr())) {
	            form.setSjr(this.getLoginUser().getUser().getUserName());
	        }
	        
	        if (StringUtils.isBlank(form.getCbyw())) {
	            WfBusTemplateForm wfBusTemplateForm = wfBusTemplateService.getByTemplateCode(getTemplateCode());
	            if (wfBusTemplateForm != null) {
	                form.setCbyw(wfBusTemplateForm.getTemplateName());
	            }
	        }

	        if (StringUtils.isBlank(form.getCbbm())) {
	            form.setCbbm("余泥处");
	        }

            if (form.getSarq() == null) {
                form.setSarq(new Date());
            }
            if (form.getSqDate() == null) {
                form.setSqDate(new Date());
            }
            if (form.getCpsj() == null) {
                form.setCpsj(new Date());
            }
            
            if(form.getFhYfrq() != null){
            	form.setFhYfrqStr(DateUtilsEX.convertDate2Chinese(form.getFhYfrq()));
            }
            if(StringUtils.isNotBlank(form.getGcdz())){
            	form.setGcdz2(form.getGcdz());
            }
            
        	LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
    		String username=uform.getUser().getUserName();
            //答复时间
    		if(id!=null && StringUtils.isNotBlank(this.getTemplateCode())){
        		Date date=this.wfServiceEX.getDfsjByTempleteCode(this.getTemplateCode(),Long.valueOf(id));
        		form.setDfsj(date);
        	}
        	
        	//补交告知原因
        	if(form.getBjgzyy()==null){
        		form.setBjgzyy(this.getOpinion("jbrsl"));
        	}
        	//补交告知时间
        	if(form.getBjgzsj()==null){
        		form.setBjgzsj(new Date());
        	}
        	//受理告知时间
        	if(form.getBjslsj()==null){
        		//form.setBjslsj(new Date());
        	}
        
        	//补交告知发出人
//        	if(form.getBjgzfcr()==null){
//        		form.setBjgzfcr(username);
//        	}
//            //补交告知受理人
//        	if(form.getSldwcbrxm()==null){
//        		form.setSldwcbrxm(username);
//        		
//        	}
        	//补交告知受理地点
        	if(form.getBjsljtdd()==null){
        		form.setBjsljtdd("广州市城市管理委员会");
        	}
    		
	    }
	/**
	 * ׼��ҳ��ģ��
	 */

	public YwYnJzfqwczzPfsnForm getModel() {
		return form;
	}
	
	// ����getter��setter����
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getCheckedIds() {
		return checkedIds;
	}

	public void setCheckedIds(Long[] checkedIds) {
		this.checkedIds = checkedIds;
	}
	
	public Page<YwYnJzfqwczzPfsnForm> getPage() {
		return page;
	}


	public void setPage(Page<YwYnJzfqwczzPfsnForm> page) {
		this.page = page;
	}
}
